package com.hw.one.collect.modbus.collect;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.lang.reflect.Field;
import java.text.MessageFormat;
import java.text.SimpleDateFormat;
import java.util.Collection;
import java.util.Locale;

import org.apache.log4j.Logger;

import com.hw.one.collect.config.ConditionConfig;
import com.hw.one.collect.entity.CommonData;
import com.hw.one.collect.entity.DataCollector;
import com.hw.one.collect.entity.DataTypeEnum;
import com.hw.one.collect.modbus.entity.HeavyMetalMap;
import com.hw.one.collect.modbus.entity.ModbusData;
import com.hw.one.collect.modbus.util.ModbusTcpUtil;
import com.hw.one.collect.util.ByteUtil;
import com.hw.one.collect.util.JsonUtil;
import com.hw.one.transpot.UploadDataUtil;

/**
 * @Class ModbusDefaultDataCollector
 * @Author guoshenzhen
 * @Date 2018/3/14 13:16
 */
public class ModbusDefaultDataCollector implements DataCollector<CommonData> {
	private Logger log = Logger.getLogger(this.getClass());

	@SuppressWarnings("finally")
	@Override
	public CommonData collect(String dateTime) {
		CommonData commonData = new CommonData(DataTypeEnum.MODBUS);
		try {
			ModbusData metal = getMetalFromHistoryFile(dateTime);
			if (metal == null) {
				commonData = null;
			} else {
				commonData = commonData.getCommonData(metal);
			}
		} catch (Exception e) {
			commonData = null;
		} finally {
			return commonData;
		}
	}

	/**
	 * 根据modbus协议采集数据
	 * 
	 * @return
	 * @throws Exception 
	 */
	private final ModbusData getMetalFromModdbus() throws Exception {
		String ip = ConditionConfig.get("ip", ConditionConfig.modbus);
		ip = null == ip ? "localhost" : ip;
		String portStr = ConditionConfig.get("port", ConditionConfig.modbus);
		int port = null == portStr ? 502 : Integer.valueOf(portStr);
		String slaveIdStr = ConditionConfig.get("slaveId", ConditionConfig.modbus);
		int slaveId = null == slaveIdStr ? 1 : Integer.valueOf(slaveIdStr);
		int ref = 0;
		int count = 78;
		// 通过modbus获取数据
		String data = ModbusTcpUtil.readInputRegister(ip, port, slaveId, ref, count);
		log.debug("ModbusDataJob.add  data--->>>" + data);
		if (null == data || data.trim().length() == 0) {
			return null;
		}
		String[] split = data.split("\\s");
		ModbusData metal = new ModbusData();
		if ("04".equals(split[7])) {
			String[] strArr = new String[split.length - 9];
			System.arraycopy(split, 9, strArr, 0, strArr.length);
			StringBuilder builder = new StringBuilder("");
			for (int i = 0; i < strArr.length; i++) {
				builder.append(strArr[i]);
			}
			final byte[] bytes = ByteUtil.hexStringToBytes(builder.toString());

			int[] intArr = ByteUtil.byteArr2intArr(bytes);
			// 增加采集时间
			String time = MessageFormat.format("{0}-{1}-{2} {3}:{4}:00", intArr[1] + "", (byte) (intArr[2] >> 8), (byte) (intArr[2]), (byte) (intArr[3] >> 8), (byte) (intArr[3]));
			metal.setTime(time);
			// 从第五个寄存器开始读 int[4] int[5]
			for (int i = 5, j = 1; i <= intArr.length; i = i + 2, j++) {
				double value = ModbusTcpUtil.getMetaValue(intArr[i - 1], intArr[i]);
				String s = HeavyMetalMap.METAL_MAP.get(j + "");
				if (null == s || s.trim().length() == 0) {
					continue;
				}
				Field field = ModbusData.class.getDeclaredField(s);
				if (null != field) {
					field.setAccessible(true);
					field.set(metal, value + "");
				}
			}
			return metal;
		}
		return null;
	}

	/**
	 * 根据历史文件采集重金属数据
	 * 
	 * @param faultKey
	 * @return
	 * @throws Exception 
	 */
	private final ModbusData getMetalFromHistoryFile(String dateTime) throws Exception {
		String yyyy = dateTime.substring(0, 4);
		String yyyymm = dateTime.substring(0, 8);
		String file = ConditionConfig.get("modbusHistoryPath", ConditionConfig.modbus);
		String fileName = String.format("%s%s%s%s%s.txt", file, File.separator, yyyy, File.separator, yyyymm);
		BufferedReader reader = new BufferedReader(new FileReader(fileName));
		String s;
		// 获取时间，根据该时间获取其下数据，超出return
		Collection<String> values = HeavyMetalMap.METAL_MAP.values();
		ModbusData modbusData = new ModbusData();
		String timeReg = "\\d{4}-\\d{1,2}-\\d{1,2} \\d{2}:\\d{2}:\\d{2}";
		int count = 0;
		String time = null;
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		SimpleDateFormat ymdh = new SimpleDateFormat("yyyyMMddHH");
		while (null != (s = reader.readLine()) && count < 2) {
			if (s.matches(timeReg)) {
				if (null != time) {
					break;
				}
				if (ymdh.format(sdf.parse(s)).startsWith(dateTime)) {
					if (null == time) {
						time = s;
					}
				}
			}
			if (null != time) {
				String[] split = s.split("\\s+");
				if (null == split || split.length != 2) {
					continue;
				}
				String key = split[0];
				String value = split[1];
				if (values.contains(key)) {
					Field field = ModbusData.class.getDeclaredField(key);
					field.setAccessible(true);
					field.set(modbusData, value);
				}
			}
		}
		reader.close();
		if (null == time) {
			return null;
		}
		modbusData.setTime(time);
		
		// pm2.5
		String pm25 = "";
		String pmfile = ConditionConfig.get("modbusPM25Path", ConditionConfig.modbus);
		String pmfileName = String.format("%s%s%s%s%s.txt", pmfile, File.separator, yyyy, File.separator, yyyymm);
		BufferedReader pmreader = new BufferedReader(new FileReader(pmfileName));
		while((pm25 = pmreader.readLine()) != null) {
			String[] pmdta = pm25.trim().split("\t");
			if (dateTime.equals(format(pmdta[0]))) {
				modbusData.setPM25(pmdta[1]);
				break;
			}
		}
		
		pmreader.close();
		return modbusData;
	}
	
	private String format(String primitiveTime) {
		try {
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.ENGLISH);
			SimpleDateFormat ymdh = new SimpleDateFormat("yyyyMMddHH");
			return ymdh.format(sdf.parse(primitiveTime));
		} catch (Exception e) {
			
		}
		return null;
	}
	
	public static void main(String[] args) throws Exception {
		ModbusDefaultDataCollector c = new ModbusDefaultDataCollector();
		c.collect("2019022210");
	}
}
